<template>
  <div class="create">
    <h2>{{ $route.params.id ? "编辑" : "创建" }}分类</h2>
    <el-form ref="form" :model="form" label-width="80px">
      <el-form-item label="上级分类">
        <el-select v-model="form.parent" placeholder="请选择">
          <el-option
            v-for="item in parentList"
            :key="item._id"
            :label="item.name"
            :value="item._id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="分类名称">
        <el-input v-model="form.name"></el-input>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="onSubmit">{{
          $route.params.id ? "修改保存" : "立即创建"
        }}</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  data() {
    return {
      form: {
        id: "",
        name: "",
        parent: null,
      },
      parentList: [],
    };
  },
  methods: {
    async getParent() {
      const res = await this.$http.get("common/categories");
      this.parentList = res.data.filter(i => i.parent == null);
    },
    async onSubmit() {
      console.log("submit!");
      let url = this.form.id == "" ? "common/categories" : "common/categories/edit";
      const res = await this.$http.post(url, this.form);
      console.log(res);

      this.$message({
        type: "success",
        message: this.form.id == "" ? "创建成功!" : "修改成功",
      });

      this.form = {
        id: "",
        name: "",
        parent: null,
      };
      this.getParent();
    },
    async getItem(id) {
      const res = await this.$http.get(`common/categories/${id}`);
      this.form = res.data;
      this.form.id = id
    },
  },
  created() {
    this.$route.params.id && this.getItem(this.$route.params.id);
  },
  mounted() {
    this.getParent();
  },
};
</script>